<template>
  <view class="expand-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <view class="back-button" @click="goBack">
        <text class="iconfont icon-back"></text>
      </view>
      <view class="header-title">
        <text class="title">信息化拓展</text>
        <text class="subtitle">{{ currentGroup.name || '未选择集团' }}</text>
      </view>
    </view>

    <!-- 进度概览卡片 -->
    <view class="progress-card">
      <view class="card-header">
        <text class="card-title">拓展进度</text>
        <text class="card-subtitle">{{ completedCount }}/{{ totalProjects }}项</text>
      </view>
      <view class="progress-bar-container">
        <view class="progress-bar">
          <view class="progress-fill" :style="{width: progressPercentage + '%'}"></view>
        </view>
        <text class="progress-text">{{ progressPercentage }}%</text>
      </view>
    </view>

    <!-- 项目列表 -->
    <view class="project-list">
      <view class="list-header">
        <text class="list-title">拓展项目</text>
        <view class="filter-buttons">
          <text
            :class="['filter-btn', filter === 'all' ? 'active' : '']"
            @click="setFilter('all')"
          >全部</text>
          <text
            :class="['filter-btn', filter === 'pending' ? 'active' : '']"
            @click="setFilter('pending')"
          >待拓展</text>
          <text
            :class="['filter-btn', filter === 'completed' ? 'active' : '']"
            @click="setFilter('completed')"
          >已完成</text>
        </view>
      </view>

      <view v-if="filteredProjects.length === 0" class="empty-state">
        <text class="empty-text">暂无项目数据</text>
      </view>

      <view v-else class="project-items">
        <view v-for="(project, index) in filteredProjects" :key="index" class="project-item">
          <view class="project-info">
            <view class="project-header">
              <text class="project-name">{{ project.name }}</text>
              <text
                :class="['project-status', project.status === 'completed' ? 'status-completed' : 'status-pending']"
              >{{ project.status === 'completed' ? '已完成' : '待拓展' }}</text>
            </view>
            <text class="project-desc">{{ project.description }}</text>
            <view class="project-meta">
              <text class="meta-item">
                <text class="meta-label">目标:</text>
                <text class="meta-value">{{ project.target }}</text>
              </text>
              <text class="meta-item">
                <text class="meta-label">预计完成:</text>
                <text class="meta-value">{{ project.dueDate }}</text>
              </text>
            </view>
          </view>

          <view class="project-actions">
            <view
              class="action-btn"
              @click="toggleStatus(index)"
            >{{ project.status === 'completed' ? '标记未完成' : '标记已完成' }}</view>
            <view class="action-btn edit-btn" @click="editProject(index)">编辑</view>
            <view class="action-btn delete-btn" @click="confirmDelete(index)">删除</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 添加按钮 -->
    <view class="add-button" @click="showAddProject">
      <text class="iconfont icon-add"></text>
    </view>

    <!-- 添加/编辑项目表单弹窗 -->
    <uni-popup ref="popup" type="bottom">
      <view class="form-popup">
        <view class="popup-header">
          <text class="popup-title">{{ isEditing ? '编辑项目' : '添加项目' }}</text>
          <text class="popup-close" @click="closeForm">×</text>
        </view>

        <view class="form-content">
          <view class="form-item">
            <text class="form-label required">项目名称</text>
            <input class="form-input" v-model="formData.name" placeholder="请输入项目名称" />
            <text v-if="errors.name" class="error-tip">{{ errors.name }}</text>
          </view>

          <view class="form-item">
            <text class="form-label">项目描述</text>
            <textarea class="form-textarea" v-model="formData.description" placeholder="请输入项目描述" />
          </view>

          <view class="form-item">
            <text class="form-label">拓展目标</text>
            <input class="form-input" v-model="formData.target" placeholder="请输入拓展目标" />
          </view>

          <view class="form-item">
            <text class="form-label required">预计完成日期</text>
            <picker
              class="form-picker"
              mode="date"
              :value="formData.dueDate"
              @change="onDateChange"
            >
              <view class="picker-value">{{ formData.dueDate || '请选择日期' }}</view>
            </picker>
            <text v-if="errors.dueDate" class="error-tip">{{ errors.dueDate }}</text>
          </view>

          <view class="form-item">
            <text class="form-label">项目状态</text>
            <picker class="form-picker" :range="statusOptions" @change="onStatusChange">
              <view class="picker-value">{{ formData.status === 'completed' ? '已完成' : '待拓展' }}</view>
            </picker>
          </view>
        </view>

        <view class="form-actions">
          <button class="form-button cancel-btn" @click="closeForm">取消</button>
          <button class="form-button submit-btn" @click="saveProject" :loading="submitting">保存</button>
        </view>
      </view>
    </uni-popup>

    <!-- 确认删除弹窗 -->
    <uni-popup ref="deletePopup" type="dialog">
      <uni-popup-dialog
        type="error"
        title="删除确认"
        content="确定要删除此拓展项目吗？此操作无法撤销。"
        :before-close="true"
        @confirm="deleteProject"
        @close="cancelDelete"
      ></uni-popup-dialog>
    </uni-popup>

    <!-- 操作反馈提示 -->
    <uni-popup ref="messagePopup" type="message">
      <uni-popup-message :type="messageType" :message="message" :duration="2000"></uni-popup-message>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentGroup: {},
      projects: [
        {
          id: "proj001",
          name: "5G专网部署",
          description: "为集团各部门部署5G专网，提升网络传输速度",
          target: "覆盖率达到95%以上",
          dueDate: "2023-12-31",
          status: "pending"
        },
        {
          id: "proj002",
          name: "视频会议系统升级",
          description: "升级现有视频会议系统，支持高清画质和多人会议",
          target: "完成30个会议室升级",
          dueDate: "2023-11-15",
          status: "completed"
        },
        {
          id: "proj003",
          name: "数据安全审计系统",
          description: "实施集团数据安全审计系统，加强数据安全管理",
          target: "覆盖所有核心业务系统",
          dueDate: "2024-01-20",
          status: "pending"
        }
      ],
      filter: "all",
      showAddForm: false,
      isEditing: false,
      editIndex: -1,
      deleteIndex: -1,
      formData: {
        id: "",
        name: "",
        description: "",
        target: "",
        dueDate: "",
        status: "pending"
      },
      errors: {
        name: "",
        dueDate: ""
      },
      statusOptions: ["待拓展", "已完成"],
      submitting: false,
      message: "",
      messageType: "success"
    };
  },

  computed: {
    filteredProjects() {
      if (this.filter === "all") {
        return this.projects;
      } else {
        return this.projects.filter(project => project.status === this.filter);
      }
    },

    totalProjects() {
      return this.projects.length;
    },

    completedCount() {
      return this.projects.filter(project => project.status === "completed")
        .length;
    },

    progressPercentage() {
      if (this.totalProjects === 0) return 0;
      return Math.round((this.completedCount / this.totalProjects) * 100);
    }
  },

  onLoad(options) {
    if (options.groupId) {
      // 从存储中获取当前集团信息
      try {
        const groupInfo = uni.getStorageSync("currentGroup");
        if (groupInfo) {
          this.currentGroup = JSON.parse(groupInfo);
        }
      } catch (e) {
        console.error("获取集团信息失败", e);
      }

      // 这里应该根据groupId获取该集团的拓展项目列表
      this.loadProjects(options.groupId);
    }
  },

  methods: {
    goBack() {
      uni.navigateBack();
    },

    setFilter(filterType) {
      this.filter = filterType;
    },

    toggleStatus(index) {
      const realIndex = this.getRealIndex(index);
      if (realIndex === -1) return;

      const project = this.projects[realIndex];
      project.status = project.status === "completed" ? "pending" : "completed";

      this.saveProjectsToStorage();

      // 显示操作成功提示
      this.showMessage(
        project.status === "completed" ? "已标记为完成" : "已标记为待拓展",
        "success"
      );
    },

    // 获取过滤后项目在原数组中的索引
    getRealIndex(filteredIndex) {
      if (this.filter === "all") {
        return filteredIndex;
      }

      const filteredItem = this.filteredProjects[filteredIndex];
      return this.projects.findIndex(item => item.id === filteredItem.id);
    },

    showAddProject() {
      this.isEditing = false;
      this.clearFormData();
      this.clearErrors();
      this.$refs.popup.open();
    },

    editProject(index) {
      const realIndex = this.getRealIndex(index);
      if (realIndex === -1) return;

      this.isEditing = true;
      this.editIndex = realIndex;
      this.clearErrors();

      const project = this.projects[realIndex];
      // 复制项目数据到表单
      this.formData = {
        id: project.id,
        name: project.name,
        description: project.description,
        target: project.target,
        dueDate: project.dueDate,
        status: project.status
      };

      this.$refs.popup.open();
    },

    confirmDelete(index) {
      const realIndex = this.getRealIndex(index);
      if (realIndex === -1) return;

      this.deleteIndex = realIndex;
      this.$refs.deletePopup.open();
    },

    deleteProject() {
      if (this.deleteIndex === -1) return;

      const projectName = this.projects[this.deleteIndex].name;
      this.projects.splice(this.deleteIndex, 1);
      this.saveProjectsToStorage();
      this.deleteIndex = -1;

      // 显示删除成功提示
      this.showMessage(`项目"${projectName}"已删除`, "success");
    },

    cancelDelete() {
      this.deleteIndex = -1;
    },

    closeForm() {
      this.$refs.popup.close();
    },

    clearFormData() {
      this.formData = {
        id: "",
        name: "",
        description: "",
        target: "",
        dueDate: this.getCurrentDate(),
        status: "pending"
      };
      this.editIndex = -1;
    },

    clearErrors() {
      this.errors = {
        name: "",
        dueDate: ""
      };
    },

    onDateChange(e) {
      this.formData.dueDate = e.detail.value;
      this.validateField("dueDate");
    },

    onStatusChange(e) {
      const status = e.detail.value === 0 ? "pending" : "completed";
      this.formData.status = status;
    },

    validateForm() {
      this.clearErrors();
      let isValid = true;

      if (!this.formData.name.trim()) {
        this.errors.name = "请输入项目名称";
        isValid = false;
      }

      if (!this.formData.dueDate) {
        this.errors.dueDate = "请选择预计完成日期";
        isValid = false;
      }

      return isValid;
    },

    validateField(field) {
      if (field === "name") {
        this.errors.name = !this.formData.name.trim() ? "请输入项目名称" : "";
      } else if (field === "dueDate") {
        this.errors.dueDate = !this.formData.dueDate
          ? "请选择预计完成日期"
          : "";
      }
    },

    saveProject() {
      // 表单验证
      if (!this.validateForm()) {
        return;
      }

      this.submitting = true;

      // 模拟网络请求延迟
      setTimeout(() => {
        if (this.isEditing && this.editIndex !== -1) {
          // 更新现有项目
          this.projects[this.editIndex] = {
            ...this.formData,
            id: this.formData.id || `proj${Date.now()}`
          };
          this.showMessage("项目更新成功", "success");
        } else {
          // 添加新项目
          this.projects.push({
            ...this.formData,
            id: `proj${Date.now()}`
          });
          this.showMessage("项目添加成功", "success");
        }

        // 保存到存储
        this.saveProjectsToStorage();

        this.submitting = false;
        this.closeForm();
      }, 500);
    },

    saveProjectsToStorage() {
      try {
        uni.setStorageSync(
          `projects_${this.currentGroup.id || "default"}`,
          JSON.stringify(this.projects)
        );
      } catch (e) {
        console.error("保存项目失败", e);
      }
    },

    loadProjects(groupId) {
      try {
        const storedProjects = uni.getStorageSync(
          `projects_${groupId || "default"}`
        );
        if (storedProjects) {
          this.projects = JSON.parse(storedProjects);
        }
      } catch (e) {
        console.error("获取项目列表失败", e);
      }
    },

    showMessage(msg, type = "success") {
      this.message = msg;
      this.messageType = type;
      this.$refs.messagePopup.open();
    },

    getCurrentDate() {
      const date = new Date();
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date
        .getDate()
        .toString()
        .padStart(2, "0");
      return `${year}-${month}-${day}`;
    }
  }
};
</script>

<style lang="scss">
.expand-container {
  padding: 30rpx;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;

  .back-button {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba(255, 255, 255, 0.8);
    border-radius: 50%;
    margin-right: 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

    .icon-back {
      font-size: 36rpx;
      color: #333;
    }
  }

  .header-title {
    flex: 1;

    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      display: block;
    }

    .subtitle {
      font-size: 24rpx;
      color: #666;
      margin-top: 6rpx;
      display: block;
    }
  }
}

.progress-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .card-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }

    .card-subtitle {
      font-size: 28rpx;
      color: #2979ff;
      font-weight: bold;
    }
  }

  .progress-bar-container {
    display: flex;
    align-items: center;

    .progress-bar {
      flex: 1;
      height: 16rpx;
      background-color: #edf1f7;
      border-radius: 8rpx;
      overflow: hidden;
      margin-right: 20rpx;

      .progress-fill {
        height: 100%;
        background: linear-gradient(90deg, #1989fa, #39b9fa);
        border-radius: 8rpx;
        transition: width 0.3s;
      }
    }

    .progress-text {
      font-size: 28rpx;
      color: #1989fa;
      font-weight: bold;
      width: 70rpx;
      text-align: right;
    }
  }
}

.project-list {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);

  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;

    .list-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      flex: 0 0 auto;
      width: 25%;
    }

    .filter-buttons {
      display: flex;
      justify-content: flex-end;
      flex: 1;

      .filter-btn {
        padding: 10rpx 20rpx;
        font-size: 24rpx;
        color: #666;
        margin-left: 15rpx;
        border-radius: 20rpx;
        background-color: #f5f7fa;

        &.active {
          color: #1989fa;
          background-color: rgba(25, 137, 250, 0.1);
        }
      }
    }
  }

  .empty-state {
    padding: 100rpx 0;
    text-align: center;

    .empty-text {
      color: #999;
      font-size: 28rpx;
    }
  }

  .project-items {
    .project-item {
      border-bottom: 1px solid #eee;
      padding: 30rpx 0;

      &:last-child {
        border-bottom: none;
      }

      .project-info {
        margin-bottom: 20rpx;

        .project-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16rpx;

          .project-name {
            font-size: 32rpx;
            font-weight: bold;
            color: #333;
          }

          .project-status {
            font-size: 24rpx;
            padding: 6rpx 16rpx;
            border-radius: 20rpx;

            &.status-completed {
              color: #07c160;
              background-color: rgba(7, 193, 96, 0.1);
            }

            &.status-pending {
              color: #ff9900;
              background-color: rgba(255, 153, 0, 0.1);
            }
          }
        }

        .project-desc {
          font-size: 28rpx;
          color: #666;
          margin-bottom: 16rpx;
          line-height: 1.5;
        }

        .project-meta {
          display: flex;
          flex-wrap: wrap;

          .meta-item {
            font-size: 26rpx;
            color: #666;
            margin-right: 30rpx;

            .meta-label {
              color: #999;
              margin-right: 8rpx;
            }
          }
        }
      }

      .project-actions {
        display: flex;
        justify-content: flex-end;

        .action-btn {
          padding: 12rpx 24rpx;
          border-radius: 6rpx;
          font-size: 26rpx;
          color: #1989fa;
          background-color: rgba(25, 137, 250, 0.1);
          margin-left: 20rpx;

          &.edit-btn {
            color: #666;
            background-color: #f5f7fa;
          }

          &.delete-btn {
            color: #ff4d4f;
            background-color: rgba(255, 77, 79, 0.1);
          }
        }
      }
    }
  }
}

.add-button {
  position: fixed;
  right: 40rpx;
  bottom: 40rpx;
  width: 110rpx;
  height: 110rpx;
  background: linear-gradient(135deg, #1989fa, #39b9fa);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 6rpx 16rpx rgba(25, 137, 250, 0.3);
  z-index: 10;
  transition: all 0.3s;

  &:active {
    transform: scale(0.9);
  }

  .icon-add {
    color: #fff;
    font-size: 50rpx;
    font-weight: bold;
  }
}

.form-popup {
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  overflow: hidden;

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1px solid #eee;

    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }

    .popup-close {
      font-size: 40rpx;
      color: #999;
      line-height: 1;
    }
  }

  .form-content {
    padding: 30rpx;
    max-height: 750rpx;
    overflow-y: auto;

    .form-item {
      margin-bottom: 30rpx;

      .form-label {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 16rpx;
        display: block;

        &.required:after {
          content: "*";
          color: #ff4d4f;
          margin-left: 8rpx;
        }
      }

      .form-input,
      .form-textarea,
      .form-picker {
        width: 100%;
        background-color: #f5f7fa;
        border-radius: 8rpx;
        padding: 20rpx;
        font-size: 28rpx;
        color: #333;
        box-sizing: border-box;
      }

      .form-textarea {
        height: 160rpx;
      }

      .picker-value {
        height: 70rpx;
        line-height: 70rpx;
      }

      .error-tip {
        font-size: 24rpx;
        color: #ff4d4f;
        margin-top: 8rpx;
        display: block;
      }
    }
  }

  .form-actions {
    display: flex;
    padding: 20rpx 30rpx 50rpx;

    .form-button {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      border-radius: 8rpx;
      font-size: 30rpx;

      &.cancel-btn {
        color: #666;
        background-color: #f5f7fa;
        margin-right: 20rpx;
      }

      &.submit-btn {
        color: #fff;
        background: linear-gradient(135deg, #1989fa, #39b9fa);
      }
    }
  }
}
</style> 